import { createStore } from 'vuex'

interface User {
  id: string
  username: string
  role: '学生' | '老师' | '管理员'
  // 其他用户信息...
}

interface State {
  isLoggedIn: boolean
  user: User | null
  token: string | null
}

export default createStore<State>({
  state: {
    isLoggedIn: false,
    user: null,
    token: null
  },
  getters: {
    currentUser: state => state.user,
    userRole: state => state.user?.role,
    isAuthenticated: state => state.isLoggedIn
  },
  mutations: {
    setLoggedIn(state, value: boolean) {
      state.isLoggedIn = value
    },
    setUser(state, user: User) {
      state.user = user
    },
    setToken(state, token: string) {
      state.token = token
    },
    clearAuth(state) {
      state.isLoggedIn = false
      state.user = null
      state.token = null
    }
  },
  actions: {
    // 检查登录状态并解析Token
    checkLogin({ commit, dispatch }) {
      const token = localStorage.getItem('token')
      if (token) {
        try {
          const decoded = JSON.parse(atob(token.split('.')[1]))
          
          // 检查Token是否过期
          if (decoded.exp * 1000 < Date.now()) {
            dispatch('logout')
            return
          }
          
          commit('setToken', token)
          commit('setLoggedIn', true)
          
          // 这里应该从解码的Token或API获取用户信息
          const user: User = {
            id: decoded.sub || '',
            username: decoded.username || '',
            role: decoded.role || '学生' // 默认学生角色
          }
          commit('setUser', user)
        } catch (error) {
          console.error('Token解析失败:', error)
          dispatch('logout')
        }
      } else {
        commit('setLoggedIn', false)
      }
    },
    
    // 登录操作
    async login({ commit }, { token, user }: { token: string; user: User }) {
      localStorage.setItem('token', token)
      commit('setToken', token)
      commit('setUser', user)
      commit('setLoggedIn', true)
    },
    
    // 登出操作
    logout({ commit }) {
      localStorage.removeItem('token')
      commit('clearAuth')
    },
    
    // 检查权限
    checkPermission({ state }, requiredRoles: string[]) {
      if (!state.user?.role) return false
      return requiredRoles.includes(state.user.role)
    }
  },
  modules: {}
})